<?php
class Code{
	private $width,$height,$codenum;   //验证码宽度、高度、字数
	public  $codechar;                //产生的验证码
	private $codeimage;               //验证码图片
	private $pointColor = '';           //干扰像素
	private $fontSize=12;

	function __construct($width='120',$height='90',$codenum='4'){
		$this->width=$width;
		$this->height=$height;
		$this->codenum=$codenum;
	}

	function outImg(){
		$this->outFileHeader();         //输出头

		$this->createCode();            //产生验证码

		$this->createImage();           //产生图片

		$this->setPointColor();       //设置干扰像素

		$this->writeCode(); //往图片上写验证码

		imagepng($this->codeimage);
		imagedestroy($this->codeimage);
	}
	/*
	 * 输出头文件 outFileHeader()
	 */
	private function outFileHeader()
	{
		header ("Content-type: image/png");
	}
	/*
	 * 产生验证码
	 */
	private function createCode()
	{
		$this->codechar =substr(md5(rand()),0,$this->codenum);
	}
	/*
	 * 产生验证码图片
	 */
	private function createImage()
	{
		$this->codeimage = &imagecreate($this->width,$this->height);
		imagecolorallocate($this->codeimage,255,255,255);

	}
	/*
	 * 设置图片的干扰像素
	 */
	private function setPointColor()
	{
		for ($i=0;$i<=250;$i++)
		{
			$this->pointColor = imagecolorallocate($this->codeimage, 200, 200, 200);
			imagesetpixel($this->codeimage,rand(0,$this->width),rand(0, $this->height),$this->pointColor);
		}
	}
	/*
	 *
	 * 在验证码图画上验证码
	 *
	 */
	private function writeCode()

	{
		$red=imagecolorallocate($this->codeimage, 255, 0, 0);
		imagettftext($this->codeimage,$this->fontSize, 0, 25, 20, $red, "../data/font/msyh.ttf",$this->codechar);

		//imagestring($this->codeimage,5, 10,4,$this->codechar,$red);

	}
	function __destruct()
	{
		unset($this->width,$this->height,$this->codenum);
	}
}
?>